﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Controllers;
using Common.Logging;
using OutDbContext;
using User.Api.Dto.Paper;
using User.Api.Helpers;

namespace User.Api.Controllers
{
    public class PaperController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(PaperController));
        private GdsfybjyWeiXinEntities _ctx;

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            _ctx = new GdsfybjyWeiXinEntities();
            base.Initialize(controllerContext);
        }

        protected override void Dispose(bool disposing)
        {
            _ctx.Dispose();
            base.Dispose(disposing);
        }

        /// <summary>
        /// 获取满意度调查列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetAll")]
        public GetAllResponse GetAll()
        {
            var azUser = AzUser.GetInApi(Request);
            var openId = azUser.OpenId;
            var wxUserId = azUser.UserId;
            var investigatePaperList = (from sps in _ctx.SIWaitInvestigatePapers
                join hcs in _ctx.HospCards on sps.PatientId equals hcs.PatientId into temp
                from tt in temp.DefaultIfEmpty()
                where tt.WxUserId == wxUserId && sps.Status == 0 && tt.DeleteStatus == 0 && tt.CardStatus == 1
                select new PaperModel
                {
                    Id = sps.Id,
                    CreateTime = sps.CreateTime,
                    CardNo = sps.CardNo,
                    Name = sps.Name,
                    OpenId = openId,
                }).OrderByDescending(x => x.CreateTime).Take(10).ToList();

            var waitPages = investigatePaperList.Select(x => new GetAllResponse.Paper
            {
                Id = x.Id,
                Name = x.CardNo,
                CreateTime = x.CreateTime?.ToString("yyyy-MM-dd") ?? "",
                CardNo = x.CardNo
            }).ToList();

            var completedPaperList = 
                _ctx.SIWaitInvestigatePapers.Where(x => 
                x.SubmitOpenId == openId && (x.Status & 0x1) == 0x1)
                .OrderByDescending(x => x.CreateTime).Take(10).ToList();

            var completedPapers = completedPaperList.Select(x => new GetAllResponse.Paper
            {
                Id = x.Id,
                Name = x.CardNo,
                CreateTime = x.CreateTime?.ToString("yyyy-MM-dd") ?? "",
                CardNo = x.CardNo,
                SubmitTime = x.SubmitTime?.ToString("yyyy-MM-dd") ?? ""
            }).ToList();

            var response = new GetAllResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                WaitingPapers = waitPages,
                CompletePapers = completedPapers
            };
            return response;
        }

        /// <summary>
        /// 获取满意度调查明细
        /// </summary>
        /// <param name="paperId"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetInvestigatePaper")]
        public GetInvestigatePaperResponse GetInvestigatePaper(int paperId)
        {
            //var azUser = AzUser.GetInApi(Request);
            var isExist = _ctx.SIWaitInvestigatePapers.Any(x => x.Id == paperId && x.Status == 0);
            if (!isExist)
            {
                return new GetInvestigatePaperResponse
                {
                    ResultCode = "1",
                    ResultMsg = "问卷不存在!"
                };
            }

            var response = new GetInvestigatePaperResponse
            {
                ResultCode = "0",
                ResultMsg = ""
            };
            response.Questions = new Dictionary<string, GetInvestigatePaperResponse.UserAnswer>();
            response.Questions.Add("FuWuTaiDu", new GetInvestigatePaperResponse.UserAnswer() { Question = "FuWuTaiDu" });
            response.Questions.Add("JiuZhenLiuChen", new GetInvestigatePaperResponse.UserAnswer() { Question = "JiuZhenLiuChen" });
            response.Questions.Add("DengHouShiJian", new GetInvestigatePaperResponse.UserAnswer() { Question = "DengHouShiJian" });
            response.Questions.Add("HuanJinWeiSheng", new GetInvestigatePaperResponse.UserAnswer() { Question = "HuanJinWeiSheng" });
            response.Questions.Add("YiDeYiFeng", new GetInvestigatePaperResponse.UserAnswer() { Question = "YiDeYiFeng" });
            response.Questions.Add("ZhongTiPingJia", new GetInvestigatePaperResponse.UserAnswer() { Question = "ZhongTiPingJia" });
            var questions = _ctx.SIUserAnswers.Where(x => x.PaperId == paperId).ToList();
            foreach (var siUserAnswer in questions)
            {
                response.Questions[siUserAnswer.Question] = new GetInvestigatePaperResponse.UserAnswer
                {
                    Id = siUserAnswer.Id,
                    PaperId = paperId,
                    Question = siUserAnswer.Question,
                    Answer = siUserAnswer.Answer
                };
            }
            return response;
        }

        /// <summary>
        /// 提交满意度调查
        /// </summary>
        /// <param name="paperId">问卷Id</param>
        /// <param name="socre1">得分1</param>
        /// <param name="socre2">得分2</param>
        /// <param name="socre3">得分3</param>
        /// <param name="socre4">得分4</param>
        /// <param name="socre5">得分5</param>
        /// <param name="socre6">得分6</param>
        /// <param name="answer">答案</param>
        /// <param name="phone">手机号码</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("SubmitPingJia")]
        public SubmitPingJiaResponse SubmitPingJia(int paperId, int socre1, int socre2, int socre3, int socre4, int socre5, int socre6,
            string answer, string phone)
        {
            var azUser = AzUser.GetInApi(Request);
            var openId = azUser.OpenId;

            try
            {
                phone = System.Net.WebUtility.UrlDecode(phone);
                answer = System.Net.WebUtility.UrlDecode(answer);

                var answerList = new List<SIUserAnswer>()
                {
                    new SIUserAnswer()
                        {
                            AddDt = DateTime.Now,
                            Answer = socre1.ToString(),
                            Question = "FuWuTaiDu",
                            PaperId = paperId,
                        },
                    new SIUserAnswer()
                        {
                            AddDt = DateTime.Now,
                            Answer = socre2.ToString(),
                            Question = "JiuZhenLiuChen",
                            PaperId = paperId,
                        },
                    new SIUserAnswer()
                        {
                            AddDt = DateTime.Now,
                            Answer = socre3.ToString(),
                            Question = "DengHouShiJian",
                            PaperId = paperId,
                        },
                    new SIUserAnswer()
                        {
                            AddDt = DateTime.Now,
                            Answer = socre4.ToString(),
                            Question = "HuanJinWeiSheng",
                            PaperId = paperId,
                        },
                    new SIUserAnswer()
                        {
                            AddDt = DateTime.Now,
                            Answer = socre5.ToString(),
                            Question = "YiDeYiFeng",
                            PaperId = paperId,
                        },
                    new SIUserAnswer()
                        {
                            AddDt = DateTime.Now,
                            Answer = socre6.ToString(),
                            Question = "ZhongTiPingJia",
                            PaperId = paperId,
                        },
                    new SIUserAnswer()
                        {
                            AddDt = DateTime.Now,
                            Answer = answer,
                            Question = "就医体验",
                            PaperId = paperId,
                        },
                    new SIUserAnswer()
                        {
                            AddDt = DateTime.Now,
                            Answer = phone,
                            Question = "联系方式",
                            PaperId = paperId,
                        }
                };

                _ctx.SIUserAnswers.AddRange(answerList);

                var paper = _ctx.SIWaitInvestigatePapers.FirstOrDefault(x => x.Id == paperId);
                if (paper != null)
                {
                    paper.Status = 1;
                    paper.SubmitCount = paper.SubmitCount + 1;
                    paper.SubmitOpenId = openId;
                    paper.SubmitTime = DateTime.Now;
                }
                _ctx.SaveChanges();

            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("提交满意度调查 出错，原因：{0}", ex.Message);

                return new SubmitPingJiaResponse()
                {
                    ResultCode = "1",
                    ResultMsg = ""
                };
            }

            return new SubmitPingJiaResponse()
            {
                ResultCode = "0",
                ResultMsg = ""
            };
        }
    }

    public class PaperModel
    {
        public int Id { get; set; }

        public DateTime? CreateTime { get; set; }

        public string CardNo { get; set; }

        public string Name { get; set; }

        public string OpenId { get; set; }
    }
}
